package com.kanshu.ksgb.fastread.doudou.common.net.retrofit;

import java.util.HashMap;
import java.util.Map;

/**
 * retrofit帮助类
 * Created by wcy on 2017/4/20.
 */
public class RetrofitHelper {
    private volatile static RetrofitHelper sRetrofitHelper;
    private BaseRetrofit mRetrofit;
    private Map<String, BaseRetrofit> mRetofitMap;
    private RetrofitHelper() {
        mRetrofit = new SimpleRetrofit();
        mRetofitMap = new HashMap();
        mRetofitMap.put(mRetrofit.getClass().getName(), mRetrofit);
    }

    public void setRetrofit(BaseRetrofit retrofit) {
        mRetrofit = retrofit;
    }

    public <T> T createService(Class<T> clazz) {
        return createService(SimpleRetrofit.class, clazz);
    }

    public <T> T createService(Class<? extends BaseRetrofit> clazzRetrofit, Class<T> clazzService) {
        T service ;
        BaseRetrofit wrapRetrofit = getWrapRetrofit(clazzRetrofit);
        if (wrapRetrofit != null) {
            service = wrapRetrofit.createService(clazzService);
            return service;
        }
        service = mRetrofit.create(clazzService);
        return service;
    }

    public static RetrofitHelper getInstance() {
        if (sRetrofitHelper == null) {
            synchronized (RetrofitHelper.class) {
                if (sRetrofitHelper == null) {
                    sRetrofitHelper = new RetrofitHelper();
                }
            }
        }
        return sRetrofitHelper;
    }

    /**
     * 获取实例对象
     * @param tClass
     * @return
     */
    private BaseRetrofit getWrapRetrofit(Class<? extends BaseRetrofit> tClass) {
        BaseRetrofit baseRetrofit = mRetofitMap.get(tClass.getName());
        if (baseRetrofit != null) {
            return baseRetrofit;
        }
        try {
            BaseRetrofit retrofit = tClass.newInstance();
            if (retrofit != null) {
                mRetofitMap.put(tClass.getName(), retrofit);
            }
            return retrofit;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
